package net.aiion.weave.impl.resources.provider;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import net.aiion.weave.impl.resources.ResourceImpl;
import net.aiion.weave.spi.resources.Resource;
import net.aiion.weave.spi.resources.ResourceException;
import net.aiion.weave.spi.resources.provider.ResourceProvider;

public class JarResourceProvider implements ResourceProvider
{
    private URL url;

    public JarResourceProvider(final URL aURL) {
        url = aURL;
    }

    @Override
    public Iterator<Resource> iterator() {
        return loadResources().iterator();
    }

    private Collection<Resource> loadResources() {
        try {
            return loadResources1();
        } catch (final IOException | URISyntaxException e) {
            throw new ResourceException(e);
        }
    }

    private Collection<Resource> loadResources1() throws IOException, URISyntaxException {
        final Collection<Resource> resources = new ArrayList<>();
        final Enumeration<JarEntry> entries = new JarFile(new File(url.toURI())).entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }

            resources.add(new ResourceImpl(entry.getName(), new URL("jar:" + url.toExternalForm() + "!/"
                + entry.getName())));
        }

        return Collections.unmodifiableCollection(resources);
    }
}
